<template>
  <div class="login">
    <!-- 头部navbar -->
    <van-nav-bar title="黑马头条-登录" class="title">
      <template #left>
        <img src="@/assets/images/logo.png" alt="" />
      </template>
    </van-nav-bar>
    <!-- 登录form表单验证 -->
    <van-form @submit="onSubmit">
      <!-- 通过 pattern 进行正则校验 -->
      <van-field
        autocomplete="off"
        v-model="formLogin.mobile"
        name="mobile"
        type="tel"
        label="手机号"
        placeholder="请输入手机号"
        required
        :rules="[
          {
            pattern: /^1[3456789]\d{9}$/,
            message: '请输入正确的手机号',
            trigger: 'onChange',
          },
        ]"
      />
      <van-field
        autocomplete="off"
        v-model="formLogin.code"
        name="code"
        type="password"
        label="密码"
        placeholder="请输入密码"
        required
        :rules="[
          {
            pattern: /^\d{6}$/,
            message: '请输入正确的密码',
            trigger: 'onChange',
          },
        ]"
      />
      <div style="margin: 16px">
        <van-button
          round
          block
          type="info"
          native-type="submit"
          :loading="isloading"
          loading-text="加载中..."
          >提交</van-button
        >
      </div>
    </van-form>
  </div>
</template>

<script>
import { mapActions } from 'vuex'
export default {
  // 组件名称
  name: 'login',
  // 组件参数 接收来自父组件的数据
  props: {},
  // 局部注册的组件
  components: {},
  // 组件状态值
  data () {
    return {
      // 用户手机号和密码
      formLogin: {
        mobile: '',
        code: ''
      },
      isloading: false
    }
  },
  methods: {
    ...mapActions(['asyncLoginActions']),
    async onSubmit () {
      this.isloading = true
      try {
        // 登录请求
        await this.asyncLoginActions(this.formLogin)
        this.$toast.setDefaultOptions({ duration: 1000 })
        // 如果有路径传值,就push到token失效时的路由页面,没有就默认到home主页
        this.$router.replace(this.$route.query.from || '/layout/home')
        this.$toast.success('登陆成功')
      } catch (error) {
        this.$toast.fail('登陆失败')
      } finally {
        // 不管最后有没有登录成功,都把按钮改成正常状态,不显示loading状态,loading是为了防止用户多次点击提交无效请求
        this.isloading = false
      }
    }
  }
}
</script>
<style scoped lang="less">
img {
  width: 100px;
  height: 30px;
}
</style>
